#pragma once

#include <chrono>
#include <vector>
#include <string>
#include <memory>
#include <mutex>

namespace viml {

/**
 * 垃圾回收统计信息收集器
 * 提供详细的GC性能和行为分析
 */
class GCStatisticsCollector {
public:
    // 单次收集周期的详细信息
    struct CollectionCycle {
        std::chrono::high_resolution_clock::time_point start_time;
        std::chrono::high_resolution_clock::time_point end_time;
        double duration_ms = 0.0;

        // 标记阶段统计
        double mark_phase_ms = 0.0;
        size_t objects_marked = 0;
        size_t roots_marked = 0;
        size_t worklist_processed = 0;

        // 清除阶段统计
        double sweep_phase_ms = 0.0;
        size_t objects_swept = 0;
        size_t bytes_swept = 0;

        // 分代统计
        size_t young_gen_before = 0;
        size_t young_gen_after = 0;
        size_t young_gen_collected = 0;
        size_t old_gen_before = 0;
        size_t old_gen_after = 0;
        size_t old_gen_collected = 0;

        // 内存统计
        size_t heap_size_before = 0;
        size_t heap_size_after = 0;
        size_t heap_size_freed = 0;

        // 触发原因
        enum class TriggerReason {
            MANUAL,              // 手动触发
            THRESHOLD,          // 内存阈值触发
            INCREMENTAL_STEP,    // 增量收集步骤
            PERIODIC,           // 定期触发
            EMERGENCY           // 紧急触发
        } trigger_reason = TriggerReason::MANUAL;

        // 收集类型
        bool is_incremental = false;
        bool is_concurrent = false;
    };

    // 内存分配统计
    struct AllocationStats {
        size_t total_allocations = 0;
        size_t total_deallocations = 0;
        size_t current_allocations = 0;
        size_t peak_allocations = 0;

        // 按类型统计
        size_t string_allocations = 0;
        size_t list_allocations = 0;
        size_t dict_allocations = 0;
        size_t function_allocations = 0;
        size_t other_allocations = 0;

        // 大小统计
        size_t total_bytes_allocated = 0;
        size_t total_bytes_freed = 0;
        size_t current_bytes_allocated = 0;
        size_t peak_bytes_allocated = 0;

        // 平均对象大小
        double avg_object_size = 0.0;
        size_t min_object_size = SIZE_MAX;
        size_t max_object_size = 0;
    };

    // GC性能统计
    struct PerformanceStats {
        double total_gc_time_ms = 0.0;
        double avg_gc_time_ms = 0.0;
        double min_gc_time_ms = 0.0;
        double max_gc_time_ms = 0.0;

        // 频率统计
        size_t total_collections = 0;
        double collections_per_second = 0.0;
        double avg_interval_ms = 0.0;

        // 效率统计
        double objects_per_ms = 0.0;
        double bytes_per_ms = 0.0;
        double mark_sweep_ratio = 0.0;

        // 增量收集统计
        size_t incremental_collections = 0;
        size_t total_incremental_steps = 0;
        double avg_incremental_step_time_ms = 0.0;
        double incremental_efficiency = 0.0;
    };

    // 根集统计
    struct RootSetStats {
        size_t total_roots = 0;
        size_t unique_objects = 0;
        size_t stack_roots = 0;
        size_t global_roots = 0;
        size_t register_roots = 0;
        size_t internal_roots = 0;
        size_t user_roots = 0;

        // 性能统计
        double avg_add_time_us = 0.0;
        size_t duplicate_removals = 0;
        size_t batch_operations = 0;

        // 增长趋势
        std::vector<size_t> root_count_history;
        std::vector<std::chrono::high_resolution_clock::time_point> timestamp_history;
        static constexpr size_t MAX_HISTORY_SIZE = 100;
    };

private:
    // 收集周期历史
    std::vector<std::unique_ptr<CollectionCycle>> collection_history_;
    std::vector<CollectionCycle*> incremental_cycles_; // 当前进行中的增量收集

    // 统计数据
    AllocationStats allocation_stats_;
    PerformanceStats performance_stats_;
    RootSetStats root_set_stats_;

    // 时间统计
    std::chrono::high_resolution_clock::time_point start_time_;
    std::chrono::high_resolution_clock::time_point last_collection_time_;

    // 线程安全
    mutable std::mutex stats_mutex_;

    // 内部辅助方法
    void update_performance_stats();
    void finalize_current_cycle();

public:
    GCStatisticsCollector();
    ~GCStatisticsCollector() = default;

    // 收集周期管理
    CollectionCycle* start_collection_cycle(CollectionCycle::TriggerReason reason, bool is_incremental = false);
    void finish_collection_cycle(CollectionCycle* cycle);
    CollectionCycle* get_current_cycle() const;

    // 标记阶段统计
    void record_mark_phase_start(CollectionCycle* cycle);
    void record_mark_phase_end(CollectionCycle* cycle);
    void record_object_marked(CollectionCycle* cycle);
    void record_root_marked(CollectionCycle* cycle);
    void record_worklist_processed(CollectionCycle* cycle, size_t count);

    // 清除阶段统计
    void record_sweep_phase_start(CollectionCycle* cycle);
    void record_sweep_phase_end(CollectionCycle* cycle);
    void record_object_swept(CollectionCycle* cycle, size_t bytes = 0);

    // 内存统计
    void record_allocation(const std::string& type, size_t size);
    void record_deallocation(const std::string& type, size_t size);
    void record_heap_size(size_t size);

    // 根集统计
    void record_root_set_stats(const RootSetStats& stats);
    void record_root_operation(double operation_time_us, bool is_batch = false, bool is_duplicate = false);

    // 获取统计信息
    AllocationStats get_allocation_stats() const;
    PerformanceStats get_performance_stats() const;
    RootSetStats get_root_set_stats() const;

    const std::vector<std::unique_ptr<CollectionCycle>>& get_collection_history() const;
    size_t get_collection_count() const;
    std::chrono::milliseconds get_uptime() const;

    // 分析和报告
    struct Analysis {
        // 内存趋势分析
        enum class MemoryTrend {
            STABLE,    // 稳定
            GROWING,    // 增长
            SHRINKING,  // 收缩
            FLUCTUATING // 波动
        } memory_trend = MemoryTrend::STABLE;

        double memory_growth_rate = 0.0; // 每秒增长率
        size_t predicted_peak_memory = 0;

        // GC性能分析
        bool is_gc_bottleneck = false;
        double gc_overhead_percentage = 0.0;
        std::string performance_grade; // A-F评级

        // 建议优化措施
        std::vector<std::string> optimization_suggestions;
    };

    Analysis analyze_performance() const;

    // 报告生成
    void print_summary() const;
    void print_detailed_report() const;
    void print_allocation_report() const;
    void print_performance_report() const;
    void print_root_set_report() const;
    void print_trend_analysis() const;

    std::string generate_json_report() const;
    std::string generate_csv_report() const;

    // 统计重置
    void reset_stats();
    void reset_history();

    // 配置选项
    struct Config {
        bool enable_detailed_tracking = true;
        bool enable_allocation_tracking = true;
        bool enable_root_set_tracking = true;
        bool enable_performance_analysis = true;
        size_t max_history_size = 1000;
        double gc_bottleneck_threshold = 10.0; // GC时间占比阈值(%)
    };

    Config config_;

    void set_config(const Config& new_config);
    const Config& get_config() const;
};

/**
 * 全局GC统计收集器
 * 提供单例访问接口
 */
class GlobalGCStatistics {
private:
    static std::unique_ptr<GCStatisticsCollector> instance_;
    static std::mutex instance_mutex_;

public:
    static GCStatisticsCollector& get_instance();
    static void shutdown();
    static bool is_initialized();
};

} // namespace viml